#include "threedimensioncrosssectionstandardedit1.h"
#include "ui_threedimensioncrosssectionstandardedit.h"

#include "util.h"
#include "imodule.h"

#include <QMessageBox>
#include <QRegularExpression>

#include <Sqltool.h>
#include "cadinterface.h"
#include "materialinfodialog.h"

ThreeDimensionCrossSectionStandardEdit1::ThreeDimensionCrossSectionStandardEdit1(QWidget *parent)
    : IModuleEditFrameInterface(parent)
    , ui(new Ui::ThreeDimensionCrossSectionStandardEdit)
{
    ui->setupUi(this);

    m_d->dbKeyUis = bingDBUis();

    init();//init

    connect(ui->comboBox_laminate, &QComboBox::currentTextChanged, this, &ThreeDimensionCrossSectionStandardEdit1::laminateComboBoxTextChanged);
    connect(ui->comboBox_componentType, &QComboBox::currentTextChanged, this, &ThreeDimensionCrossSectionStandardEdit1::componentTypeComboBoxTextChanged);
    connect(ui->comboBox_scale, &QComboBox::currentTextChanged, this, &ThreeDimensionCrossSectionStandardEdit1::scaleComboBoxTextChanged);
    connect(ui->comboBox_style, &QComboBox::currentTextChanged, this, &ThreeDimensionCrossSectionStandardEdit1::styleComboBoxTextChanged);
    
    connect(ui->pushButton_deleteCurve, &QPushButton::clicked, this, &ThreeDimensionCrossSectionStandardEdit1::on_pushButton_deleteCurve_clicked);

    //各个group的checkBox的折叠
    // groupCheckBoxOpenClose();
}

ThreeDimensionCrossSectionStandardEdit1::~ThreeDimensionCrossSectionStandardEdit1()
{
    delete ui;
}

//Init the view
void ThreeDimensionCrossSectionStandardEdit1::init()
{
    //初始化名称，数据库中包含”ThreeDimensionCrossSection“字符串所有名称最大值+1
    ui->lineEdit_name->setText(IModule::defName("threedimensioncrosssection", csUtil::tableName));
    ui->comboBox_laminate->setCurrentText("");
    ui->lineEdit_crossSectionCurve->setText("");
    ui->comboBox_componentType->setCurrentText("Ply");
    ui->comboBox_boundaryType->setCurrentText("Net");
    ui->comboBox_scale->setCurrentText("Scaled");
    ui->lineEdit_plyLayerScale->setText("");
    ui->lineEdit_coreScale->setText("");
    ui->comboBox_style->setCurrentText("Draped");
    ui->comboBox_profile->setCurrentText("Line");
    ui->lineEdit_minimumDistance->setText("0mm");
    ui->lineEdit_crossSectionOffset->setText("0mm");

    //各个group的checkBox的折叠
    groupCheckBoxOpenClose();

}

//各个group的checkBox的折叠
void ThreeDimensionCrossSectionStandardEdit1::groupCheckBoxOpenClose()
{
    connect(ui->Overview, &QCheckBox::stateChanged, this, [this](int state) {
        if (state == Qt::Checked) {
            ui->groupBox_1->hide();
        } else {
            ui->groupBox_1->show();
        }
    });
    connect(ui->Geometry, &QCheckBox::stateChanged, this, [this](int state) {
        if (state == Qt::Checked) {
            ui->groupBox_2->hide();
        } else {
            ui->groupBox_2->show();
        }
    });
    connect(ui->ComponentType, &QCheckBox::stateChanged, this, [this](int state) {
        if (state == Qt::Checked) {
            ui->groupBox_3->hide();
        } else {
            ui->groupBox_3->show();
        }
    });
    connect(ui->BoundaryType, &QCheckBox::stateChanged, this, [this](int state) {
        if (state == Qt::Checked) {
            ui->groupBox_4->hide();
        } else {
            ui->groupBox_4->show();
        }
    });
    connect(ui->Scale, &QCheckBox::stateChanged, this, [this](int state) {
        if (state == Qt::Checked) {
            ui->groupBox_51->hide();
            ui->groupBox_5->hide();
        } else {
            ui->groupBox_5->show();
            ui->groupBox_51->show();
        }
    });
    connect(ui->VisualSettings, &QCheckBox::stateChanged, this, [this](int state) {
        if (state == Qt::Checked) {
            ui->groupBox_6->hide();
        } else {
            ui->groupBox_6->show();
        }
    });
    connect(ui->Options, &QCheckBox::stateChanged, this, [this](int state) {
        if (state == Qt::Checked) {
            ui->groupBox_7->hide();
        } else {
            ui->groupBox_7->show();
        }
    });
}

void ThreeDimensionCrossSectionStandardEdit1::getData(QVariantMap &info)
{
    IModuleEditFrameInterface::getData(info);
    //其他的数据
    QString scaleType = ui->comboBox_componentType->currentText();
    if (scaleType.compare("Scaled", Qt::CaseInsensitive) == 0) {
        info["PlyLayerOffsetDistance"] = "";
        info["CoreOffsetDistance"] = "";
    } else if (scaleType.compare("Constant", Qt::CaseInsensitive) == 0) {
        info["PlyLayerScale"] = "";
        info["CoreScale"] = "";
    }
}

//切换laminate
void ThreeDimensionCrossSectionStandardEdit1::laminateComboBoxTextChanged(const QString & str_mappingType)
{
    Sqltool::instance().changeInfoDb();

    QPair<QString, QVariant> pair{"Name", str_mappingType};
    const auto& info = Sqltool::instance().selectOne(lamUtil::tableName, pair);
    QString designBoundary = info["DesignBoundary"].toString();

    if (designBoundary.compare("Net", Qt::CaseInsensitive) == 0) {
        ui->comboBox_boundaryType->setCurrentIndex(0);
    } else if (designBoundary.compare("Extended", Qt::CaseInsensitive) == 0) {
        ui->comboBox_boundaryType->setCurrentIndex(1);
    } else if (not str_mappingType.isEmpty()) {
        QMessageBox::warning(this, "Validation Error", "Unavle to process current type of DesignBoundary");
    }
}

//切换componentType
void ThreeDimensionCrossSectionStandardEdit1::componentTypeComboBoxTextChanged(const QString & str_mappingType)
{
    // QString componentType = ui->comboBox_componentType->currentText();
    if (str_mappingType.compare("Ply", Qt::CaseInsensitive) == 0) {
        ui->comboBox_boundaryType->setEnabled(true);
    } else if (str_mappingType.compare("Layer", Qt::CaseInsensitive) == 0) {
        ui->comboBox_boundaryType->setEnabled(false);
    } else {
        QMessageBox::warning(this, "Validation Error", "Unavle to process current component type");
    }
}

//切换scale
void ThreeDimensionCrossSectionStandardEdit1::scaleComboBoxTextChanged(const QString & str_mappingType)
{
    // QString scaleType = ui->comboBox_componentType->currentText();
    if (str_mappingType.compare("Scaled", Qt::CaseInsensitive) == 0) {
        ui->label_4->setText("Ply/Layer Scale");
        ui->label_5->setText("Core Scale");
        ui->lineEdit_plyLayerScale->setText("");
        ui->lineEdit_coreScale->setText("");

        m_d->dbKeyUis.remove("PlyLayerOffsetDistance");
        m_d->dbKeyUis.remove("CoreOffsetDistance");
        m_d->dbKeyUis["PlyLayerScale"] = ui->lineEdit_plyLayerScale;
        m_d->dbKeyUis["CoreScale"] = ui->lineEdit_coreScale;

    } else if (str_mappingType.compare("Constant", Qt::CaseInsensitive) == 0) {
        ui->label_4->setText("Ply/Layer Offset Distance");
        ui->label_5->setText("Core Offset Distance");
        ui->lineEdit_plyLayerScale->setText("");
        ui->lineEdit_coreScale->setText("");

        m_d->dbKeyUis.remove("PlyLayerScale");
        m_d->dbKeyUis.remove("CoreScale");
        m_d->dbKeyUis["PlyLayerOffsetDistance"] = ui->lineEdit_plyLayerScale;
        m_d->dbKeyUis["CoreOffsetDistance"] = ui->lineEdit_coreScale;
    } else {
        QMessageBox::warning(this, "Validation Error", "Unavle to process current scale type");
    }
}

//切换style
void ThreeDimensionCrossSectionStandardEdit1::styleComboBoxTextChanged(const QString & str_mappingType)
{
    // QString styleCType = ui->comboBox_style->currentText();
    if (str_mappingType.compare("Draped", Qt::CaseInsensitive) == 0) {
        ui->lineEdit_minimumDistance->setText("0mm");
        ui->lineEdit_crossSectionOffset->setText("0mm");
        ui->lineEdit_minimumDistance->setEnabled(true);
        ui->lineEdit_crossSectionOffset->setEnabled(true);
    } else if (str_mappingType.compare("Schematic", Qt::CaseInsensitive) == 0) {
        ui->lineEdit_minimumDistance->setText("0mm");
        ui->lineEdit_crossSectionOffset->setText("0mm");
        ui->lineEdit_minimumDistance->setEnabled(false);
        ui->lineEdit_crossSectionOffset->setEnabled(true);
    } else if (str_mappingType.compare("Over Core Hybrid", Qt::CaseInsensitive) == 0) {
        ui->lineEdit_minimumDistance->setText("0mm");
        ui->lineEdit_crossSectionOffset->setText("0mm");
        ui->lineEdit_minimumDistance->setEnabled(false);
        ui->lineEdit_crossSectionOffset->setEnabled(true);
    } else {
        QMessageBox::warning(this, "Validation Error", "Unavle to process current style type");
    }
}

// 选择 几何
void ThreeDimensionCrossSectionStandardEdit1::on_pushButton_SelectCurve_clicked()
{
    const wchar_t* filterType = L"Curve";
    char crossSectionCurve[512] = {0};
    // 调用 SelectionToID 函数
    CADInterface::instance().fibSelectiontoID(filterType,crossSectionCurve);
    ui->lineEdit_crossSectionCurve->setText(QString(crossSectionCurve));
}

//在界面中delete 几何
void ThreeDimensionCrossSectionStandardEdit1::on_pushButton_deleteCurve_clicked()
{
    // emit deleteCurve_signal();//delete信号
    ui->lineEdit_crossSectionCurve->setText("");
}

//生成 3D Cross Section
void ThreeDimensionCrossSectionStandardEdit1::on_pushButton_Generate_clicked()
{
    // 匹配可选正负号、整数部分、小数点和小数部分
    static const QRegularExpression re(R"(([-+]?[0-9]*\.?[0-9]+))");
    auto extractFloat = [&](const QString &s)->std::optional<double> {
        auto m = re.match(s);
        if (m.hasMatch()) {
            bool ok;
            double val = m.captured(1).toDouble(&ok);
            if (ok) return val;
        }
        return std::nullopt;
    };

    QString laminate_name = ui->comboBox_laminate->currentText();
    QString crossSectionCurve_name = ui->lineEdit_crossSectionCurve->text();
    QString componentType = ui->comboBox_componentType->currentText(); // Ply / Layer
    QString boundaryType = ui->comboBox_boundaryType->currentText(); // Net / Extended
    QString scaleType = ui->comboBox_scale->currentText(); // Scaled / Constant
    double plyLayerScale = 0.0;
    QString tempValue = ui->lineEdit_plyLayerScale->text();
    auto value = extractFloat(tempValue);
    if (value.has_value()) {
        plyLayerScale = value.value();
    } else{
        qDebug() << tempValue << "-> not a number";
    }
    double coreScale = 0.0;
    tempValue = ui->lineEdit_coreScale->text();
    value = extractFloat(tempValue);
    if (value.has_value()) {
        coreScale = value.value();
    } else{
        qDebug() << tempValue << "-> not a number";
    }
    QString styleType = ui->comboBox_style->currentText(); // Draped / Schematic / Over Core Hybrid
    QString profile = ui->comboBox_profile->currentText(); // line / rectangle
    double minimumDistanceType = 0.0;
    tempValue = ui->lineEdit_minimumDistance->text();
    value = extractFloat(tempValue);
    if (value.has_value()) {
        minimumDistanceType = value.value();
    } else{
        qDebug() << tempValue << "-> not a number";
    }
    double crossSectionOffset = 0.0;
    tempValue = ui->lineEdit_crossSectionOffset->text();
    value = extractFloat(tempValue);
    if (value.has_value()) {
        crossSectionOffset = value.value();
    } else{
        qDebug() << tempValue << "-> not a number";
    }
    bool createGeometry = ui->checkBox_CreateGeometry->isChecked();

    QString exeDirPath = QCoreApplication::applicationDirPath();
    exeDirPath.replace("/", "\\\\");  // 简单替换所有正斜杠

    // TODO
    CADInterface::instance().fibCreate3Dsection(laminate_name,
                                                crossSectionCurve_name,
                                                componentType,
                                                boundaryType,
                                                scaleType,
                                                plyLayerScale,
                                                coreScale,
                                                styleType,
                                                profile,
                                                minimumDistanceType,
                                                crossSectionOffset,
                                                createGeometry,
                                                "Construction",
                                                false,
                                                exeDirPath);

}

//检查所有必填项是否完成
bool ThreeDimensionCrossSectionStandardEdit1::validateForm()
{
    bool isValid = true;
    QString errorMessage;

    //Name不能为空
    if (ui->lineEdit_name->text().isEmpty()) {
        isValid = false;
        errorMessage += "Name cannot be empty.\n";
    }
    if (!isValid) {
        QMessageBox::warning(this, "Validation Error", errorMessage);
    }
    return isValid;
}

QMap<QString, QWidget *> ThreeDimensionCrossSectionStandardEdit1::bingDBUis()
{
    QMap<QString, QWidget *> ret;
    // 绑定UI控件与数据库字段
    ret["Name"] = ui->lineEdit_name;
    ret["Laminate"] = ui->comboBox_laminate;
    ret["CrossSectionCurve"] = ui->lineEdit_crossSectionCurve;
    ret["ComponentType"] = ui->comboBox_componentType;
    ret["BoundaryType"] = ui->comboBox_boundaryType;

    ret["Scale"] = ui->comboBox_scale;
    // ret["PlyLayerScale"] = ui->lineEdit_plyLayerScale;
    // ret["CoreScale"] = ui->lineEdit_coreScale;
    // ret["PlyLayerOffsetDistance"] = ui->lineEdit_plyLayerScale;
    // ret["CoreOffsetDistance"] = ui->lineEdit_coreScale;

    ret["Style"] = ui->comboBox_style;
    ret["ProfileType"] = ui->comboBox_profile;
    ret["MinimumDistance"] = ui->lineEdit_minimumDistance;
    ret["CrossSectionOffset"] = ui->lineEdit_crossSectionOffset;

    return ret;
}

QString ThreeDimensionCrossSectionStandardEdit1::title()
{
    return "Standard";
}

void ThreeDimensionCrossSectionStandardEdit1::reInitUI()
{
    ui->lineEdit_name->setEnabled(true);
    IModuleEditFrameInterface::reInitUI();

    //
    ui->comboBox_laminate->clear();
    Sqltool::instance().changeInfoDb();
    auto parentNames = Sqltool::instance().selectAllNamesByTableName(lamUtil::tableName); // ...
    ui->comboBox_laminate->addItem("");
    ui->comboBox_laminate->addItems(parentNames);
    ui->comboBox_laminate->setCurrentIndex(0);

    ui->lineEdit_name->setText(IModule::defName("threedimensioncrosssection", csUtil::tableName));

    ui->lineEdit_crossSectionCurve->setText("");
    ui->comboBox_componentType->setCurrentText("Ply");
    ui->comboBox_boundaryType->setCurrentText("Net");
    ui->comboBox_scale->setCurrentText("Scaled");
    ui->lineEdit_plyLayerScale->setText("");
    ui->lineEdit_coreScale->setText("");
    ui->comboBox_style->setCurrentText("Draped");
    ui->comboBox_profile->setCurrentText("Line");
    ui->lineEdit_minimumDistance->setText("0mm");
    ui->lineEdit_crossSectionOffset->setText("0mm");
}

void ThreeDimensionCrossSectionStandardEdit1::editUI(const QVariantMap& info) {
    ui->comboBox_laminate->setCurrentText(info["Laminate"].toString());
    ui->comboBox_componentType->setCurrentText(info["ComponentType"].toString());
    ui->comboBox_scale->setCurrentText(info["Scale"].toString());
    ui->comboBox_style->setCurrentText(info["Style"].toString());

    ui->comboBox_laminate->blockSignals(true);
    ui->comboBox_componentType->blockSignals(true);
    ui->comboBox_scale->blockSignals(true);
    ui->comboBox_style->blockSignals(true);
    IModuleEditFrameInterface::editUI(info);
    ui->comboBox_laminate->blockSignals(false);
    ui->comboBox_componentType->blockSignals(false);
    ui->comboBox_scale->blockSignals(false);
    ui->comboBox_style->blockSignals(false);

    ui->lineEdit_name->setEnabled(false);
}

void ThreeDimensionCrossSectionStandardEdit1::createBaseOn(const QVariantMap& info) {
    ui->comboBox_laminate->setCurrentText(info["Laminate"].toString());
    ui->comboBox_componentType->setCurrentText(info["ComponentType"].toString());
    ui->comboBox_scale->setCurrentText(info["Scale"].toString());
    ui->comboBox_style->setCurrentText(info["Style"].toString());

    ui->comboBox_laminate->blockSignals(true);
    ui->comboBox_componentType->blockSignals(true);
    ui->comboBox_scale->blockSignals(true);
    ui->comboBox_style->blockSignals(true);
    IModuleEditFrameInterface::editUI(info);
    ui->comboBox_laminate->blockSignals(false);
    ui->comboBox_componentType->blockSignals(false);
    ui->comboBox_scale->blockSignals(false);
    ui->comboBox_style->blockSignals(false);

    ui->lineEdit_name->setEnabled(true);
    ui->lineEdit_name->setText(IModule::defName("threedimensioncrosssection", csUtil::tableName));
}

